package com.lhz;

import com.lhz.project.system.task.TaskManager;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
 * @author lihuazhi
 */
@Component
@EnableAsync
@Slf4j
public class CustomizeApplicationContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    /**
     * 得到spring的IOC容器
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (CustomizeApplicationContext.applicationContext == null) {
            CustomizeApplicationContext.applicationContext = applicationContext;
        }
        log.info("ApplicationContext配置成功,applicationContext对象：" + CustomizeApplicationContext.applicationContext);
    }

    @PostConstruct
    public void initTask() {
        //项目启动时，进行加载
        log.info("########项目启动时，进行加载#########");
    }

    @PreDestroy
    public void destroy() {
        log.info("########项目关闭时，进行加载#########");
        // 查询运行中的任务，进行停止操作
        TaskManager taskManager = CustomizeApplicationContext.getBean(TaskManager.class);
        taskManager.clear();
    }

    /**
     * 通过bean名称获取bean实例
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 通过bean类型获取bean实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过bean名称和类型获取bean实例
     *
     * @param name  bean名称
     * @param clazz bean类型
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }
}